let xlsxUtils = module.exports = {};

let xlsx = require('xlsx');
let errinfo = require('../errinfo');
let responseJsonUtils = require('../utils/responseJsonUtils');


xlsxUtils.importParseFile = function (req, res, next) {

    try {
        let workbook = xlsx.read(req.body.file.binaryBuff, {type: 'binary'});
        let sheetNames = workbook.SheetNames;

        if (sheetNames.length === 0) {
            next(responseJsonUtils.json(errinfo.contactMember.importFileSheetsEmpty, 403));
            return;
        }

        let worksheet = workbook.Sheets[sheetNames[0]]; // only get the first sheet
        req.fileJson = xlsx.utils.sheet_to_json(worksheet);
        next();
    } catch (e) {
        next(responseJsonUtils.json(errinfo.mongodb.internalError, e));
    }
};
/**
 * convert array of arrays to worksheet
 */
xlsxUtils.sheet_from_array_of_arrays = function (data, opts) {
    let ws = {};
    let range = {s: {c: 10000000, r: 10000000}, e: {c: 0, r: 0}};
    for (let R = 0; R != data.length; ++R) {
        for (let C = 0; C != data[R].length; ++C) {
            if (range.s.r > R) range.s.r = R;
            if (range.s.c > C) range.s.c = C;
            if (range.e.r < R) range.e.r = R;
            if (range.e.c < C) range.e.c = C;
            let cell = {v: data[R][C]};
            if (cell.v == null) continue;
            let cell_ref = xlsx.utils.encode_cell({c: C, r: R});

            if (typeof cell.v === 'number') cell.t = 'n';
            else if (typeof cell.v === 'boolean') cell.t = 'b';
            else if (cell.v instanceof Date) {
                cell.t = 'n';
                cell.z = xlsx.SSF._table[14];
                cell.v = datenum(cell.v);
            }
            else cell.t = 's';

            ws[cell_ref] = cell;
        }
    }
    if (range.s.c < 10000000) ws['!ref'] = xlsx.utils.encode_range(range);
    return ws;
}